﻿/*======================================================================================================================================================

----------------BIẾN KHAI BÁO TOÀN CỤC CHƯƠNG TRÌNH

======================================================================================================================================================*/
var data = require("sdk/self").data;
var contextMenu = require("sdk/context-menu");
var tabs = require("sdk/tabs");
function PageManager() {
    this.tabIds = [];
    this.workers = [];

    this.setWorker = function (tabId, worker) {
        var index = -1;
        for (var i = 0 ; i < this.tabIds.length; i++)
            if (this.tabIds[i] == tabId) {
                index = i;
                break;
            }
        if (index == -1) {
            this.tabIds.push(tabId);
            this.workers.push(worker);
        }
        else {
            this.workers[index] = worker;
        }
    }

    this.removeWorker = function (tabId) {
        for (var i = 0 ; i < this.tabIds.length; i++)
            if (this.tabIds[i] == tabId) {
                delete this.tabIds[i];
                delete this.workers[i];
                break;
            }
    }

    this.getWorker = function (tabId) {
        var index = -1;
        for (var i = 0; i < this.tabIds.length; i++)
            if (this.tabIds[i] == tabId) {
                index = i;
                break;
            }
        if (index == -1)
            return null;
        else
            return this.workers[index];
    }
};

var pageManager = new PageManager();
var settingData;

/*======================================================================================================================================================

----------------TOGGLE BUTTON VÀ CÁC XỬ LÝ LIÊN QUAN

======================================================================================================================================================*/
var toggleButton = require("sdk/ui/button/toggle").ToggleButton({
    id: "video-preview-button-option",
    label: "To change video preview mode. Click this button",
    icon: {
        "16": "./icon/icon-toolbar-16.png",
        "32": "./icon/icon-toolbar-32.png",
        "64": "./icon/icon-toolbar-64.png"
    },
    onChange: handleChange
});

/*======================================================================================================================================================

----------------PANEL VÀ CÁC XỬ LÝ LIÊN QUAN

======================================================================================================================================================*/
var panel = require("sdk/panel").Panel({
    width: 245,
    height: 112,
    contentURL: data.url("./html/panel-menu.html"),
    onHide: handleHide
});

function handleHide() {
    toggleButton.state("window", { checked: false });
}

function handleChange(state) {
    if (state.checked) {
        panel.show({
            position: toggleButton
        });
    }
}

panel.port.on("navigateToSupportPage", function () {
    panel.hide();
    tabs.open("http://supportvideopreview.wordpress.com/");
});


panel.port.on("reload-setting-data", function (value) {
    settingData = value;
    if (settingData != null) {
        var curWorker = pageManager.getWorker(tabs.activeTab.id);
        var exceptThisSite = true;

        if (settingData.isExceptedAllSites == 1) {
            exceptThisSite = true;
            if (settingData.countAcceptedSites > 0)
                for (var i = 0; i < settingData.countAcceptedSites; i++) {
                    if (settingData.acceptedSites[i] == tabs.activeTab.url) {
                        exceptThisSite = false;
                        break;
                    }
                }
        } else {
            exceptThisSite = false;
            if (settingData.countExceptedSites > 0)
                for (var i = 0; i < settingData.countExceptedSites; i++) {
                    if (settingData.exceptedSites[i] == tabs.activeTab.url) {
                        exceptThisSite = true;
                        break;
                    }
                }
        }
        if (exceptThisSite == true && curWorker != null)
            curWorker.port.emit("except-site");
        else
            if (exceptThisSite == false && curWorker != null)
                curWorker.port.emit("accept-site");
    }
});


/*======================================================================================================================================================

----------------CONTEXT-MENU VÀ CÁC XỬ LÝ LIÊN QUAN

======================================================================================================================================================*/

contextMenu.Menu({
    label: "Video Preview",
    image: data.url("./icon/icon-toolbar-16.png"),
    items: [
        contextMenu.Item({
            label: "Play",
            image: data.url("./icon/play.png"),
            contentScript: 'self.on("click", function () {' +
                           '  self.postMessage();' +
                           '});',
            onMessage: function (value) {
                var curWorker = pageManager.getWorker(tabs.activeTab.id);
                if (curWorker != null)
                    curWorker.port.emit("play-video");
            }
        }),
        contextMenu.Item({
            label: "Pause",
            image: data.url("./icon/pause.png"),
            contentScript: 'self.on("click", function () {' +
                           '  self.postMessage();' +
                           '});',
            onMessage: function (value) {
                var curWorker = pageManager.getWorker(tabs.activeTab.id);
                if (curWorker != null)
                    curWorker.port.emit("pause-video");
            }
        }),
        contextMenu.Item({
            label: "Stop",
            image: data.url("./icon/stop.png"),
            contentScript: 'self.on("click", function () {' +
                          '  self.postMessage();' +
                          '});',
            onMessage: function (value) {
                var curWorker = pageManager.getWorker(tabs.activeTab.id);
                if (curWorker != null)
                    curWorker.port.emit("stop-video");
            }
        }),
        contextMenu.Separator(),
        contextMenu.Item({
            label: "Except this site",
            contentScript: 'self.on("click", function () {' +
                         '  self.postMessage();' +
                         '});',
            onMessage: function (value) {
                panel.port.emit("require-except-site", tabs.activeTab.url);
            }
        }),
        contextMenu.Item({
            label: "Accept this site",
            contentScript: 'self.on("click", function () {' +
                         '  self.postMessage();' +
                         '});',
            onMessage: function (value) {
                panel.port.emit("require-accept-site", tabs.activeTab.url);
            }
        })
    ]
});
/*======================================================================================================================================================

----------------TABS VÀ CÁC XỬ LÝ LIÊN QUAN

======================================================================================================================================================*/
tabs.on("close", function (tab) {
    pageManager.removeWorker(tab.id);
});

tabs.on("activate", function (tab) {
    if (settingData != null) {
        var curWorker = pageManager.getWorker(tab.id);
        var exceptThisSite;

        if (settingData.isExceptedAllSites == 1) {
            exceptThisSite = true;
            if (settingData.countAcceptedSites > 0)
                for (var i = 0; i < settingData.countAcceptedSites; i++) {
                    if (settingData.acceptedSites[i] == tab.url) {
                        exceptThisSite = false;
                        break;
                    }
                }
        } else {
            exceptThisSite = false;
            if (settingData.countExceptedSites > 0)
                for (var i = 0; i < settingData.countExceptedSites; i++) {
                    if (settingData.exceptedSites[i] == tab.url) {
                        exceptThisSite = true;
                        break;
                    }
                }
        }
        if (exceptThisSite == true && curWorker != null)
            curWorker.port.emit("except-site");
        else
            if (exceptThisSite == false && curWorker != null)
                curWorker.port.emit("accept-site");
    }
});

tabs.on("pageshow", function (tab) {
    var jsFile = "./js/support/video-action-default.js";

    var link = tab.url;
    if (link.search("https://www.youtube.com/") == 0)
        jsFile = "./js/support/video-action-youtube.com.js";
    if (link.search("http://tv.zing.vn/") == 0)
        jsFile = "./js/support/video-action-tv.zing.vn.js";
    if (link.search("http://dantri.com.vn/") == 0)
        jsFile = "./js/support/video-action-dantri.com.vn.js";
    if (link.search("http://phimvang.org/") == 0)
        jsFile = "./js/support/video-action-phimvang.org.js";
    if (link.search("http://phim47.com/") == 0)
        jsFile = "./js/support/video-action-phim47.com.js";

    var curWorker = tab.attach({
        contentScriptFile: [data.url("./js/jquery-1.11.1.min.js"), data.url(jsFile)]
    });
    pageManager.setWorker(tab.id, curWorker);

    if (settingData != null) {
        var curWorker = pageManager.getWorker(tab.id);
        var exceptThisSite;

        if (settingData.isExceptedAllSites == 1) {
            exceptThisSite = true;
            if (settingData.countAcceptedSites > 0)
                for (var i = 0; i < settingData.countAcceptedSites; i++) {
                    if (settingData.acceptedSites[i] == tab.url) {
                        exceptThisSite = false;
                        break;
                    }
                }
        } else {
            exceptThisSite = false;
            if (settingData.countExceptedSites > 0)
                for (var i = 0; i < settingData.countExceptedSites; i++) {
                    if (settingData.exceptedSites[i] == tab.url) {
                        exceptThisSite = true;
                        break;
                    }
                }
        }

        if (exceptThisSite == true && curWorker != null) {
            curWorker.port.emit("analize-page", tab.url);
            curWorker.port.emit("except-site");
        }
        if (exceptThisSite == false && curWorker != null) {
            curWorker.port.emit("analize-page", tab.url);
            curWorker.port.emit("accept-site");
        }
    }

});